package utils;

import java.util.Hashtable;
import java.util.concurrent.ExecutionException;

import com.example.android.google.apis.com.example.android.apis.MapsDemo;

import views.DialogLauncher;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;

import docks.Dock;

public class DataDownloader {

    private static Context ctx;
    private Hashtable<Integer, Dock> dockList;
    public boolean dataReady;
    private DownloadBicingData dbd;

    public DataDownloader() {

	dataReady = false;
	dbd = new DownloadBicingData();
    }

    public Hashtable<Integer, Dock> download() {

	Log.v("CHIVATO","Executant thread!!");
	ProgressDialog pd = ProgressDialog.show(ctx, "gBicing", "Working...",true, false);
	dbd.execute();
//	Intent intent = new Intent(ctx, views.DockTab.class);
//	ctx.startActivity(intent);
//	DialogLauncher.launchDialog();
	try {
	   dockList = dbd.get();
	} catch (Exception e) {
	   
	    ShowException.show(ctx, e);
	}
	pd.dismiss();
//	DialogLauncher.dismissDialog();
	return dockList;
    }

    private class DownloadBicingData extends
	    AsyncTask<Void, Void, Hashtable<Integer, Dock>> {

	@Override
	protected Hashtable<Integer, Dock> doInBackground(Void... arg0) {

	    Hashtable<Integer, Dock> list = null;

	    try {
		String html = HTML
			.doConnection("http://www.bicing.cat/localizaciones/localizaciones.php?TU5fTE9DQUxJWkFDSU9ORVM%3D&MQ%3D%3D");
		String xml = HTML.extractXml(html, "<Document>", "</Document>");
		xmlparser.SaxParser sax = new xmlparser.SaxParser(xml);
		sax.parseBicingState();
		list = sax.getDockList();
		dataReady = true;
	    } catch (Exception e) {
		ShowException.show(ctx, e);
	    }

	    return list;
	}

    }

    public static void setContext(Context c) {

	ctx = c;
    }

    public Hashtable<Integer, Dock> getDockList() {

	DialogLauncher.launchDialog();
	try {
	   dockList = dbd.get();
	} catch (Exception e) {
	   
	    ShowException.show(ctx, e);
	}
	DialogLauncher.dismissDialog();
	return dockList;
    }
}
